其他
Spring纯注解开发,有点强!!
点击“终码一生”,关注,置顶公众号
每日技术干货,第一时间送达!
1
前言Spring3.0引入了纯注解开发的模式,框架的诞生是为了简化开发,那注解开发就是简化再简化。Spring的特性在整合MyBatis方面体现的淋漓尽致哦
2
注解开发以前跟老韩学习SE时他就说:
3
注解定义Bean注解开发前,配置Bean时是在xml里将class分别写在Bean标签里,然后起id,就像这样
<bean id="a" class="yu7daily.Dao.Daoimpl.A" />
注解开发后,配置Bean时首先将xml里的<Bean>标签删掉,然后在类上添加@Component注解即可
@Component("a")
public class A implements AA {
public void save() {
System.out.println("book dao save ..." );
}
}
<context:component-scan base-package="yu7daily.Dao"/>
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
A aa = (A) ctx.getBean("a");
bookService.save();
}
4
衍生注解对于@Component还有衍生的三个注解:
5
纯注解开发模式@Configuration
@ComponentScan("yu7daily")
public class Config {...}
@Component("a")
@Scope("prototype")
public class A implements AA {
public void save() {
System.out.println("hello~");
}
}
6
注解实现注入@Service
public class A implements AA {
@Autowired
private B b;
}
@Repository("b")
public class B implements BB {
@Autowired
@Qualifier("a") //注入指定的对象名称
private AA aa;
public void save() {
aa.save();
}
}
@Repository("a")
public class A implements AA {
@Value("hello java")
private String str;
public void save() {
System.out.println(str);
}
}
运行结果:hello
@Configuration
@ComponentScan("yu7daily")
@PropertySource("test.properties")
public class SpringConfig {
}
@Repository("a")
public class A implements AA {
@Value("${name}")
private String str;
public void save() {
System.out.println(str);
}
}
运行结果:lanyangyang
7
Spring整合MyBatis<artifactId>spring-jdbc</artifactId>和13<artifactId>mybatis-spring</artifactId>
@Configuration
@ComponentScan("yu7daily")
@PropertySource("classpath:jdbc.properties")
4@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {...}
ApplicationContext ACC = new AnnotationConfigApplicationContext(SpringConfig.class);
AccountService acc = ACC.getBean(AccountService.class);
往期推荐